#!/usr/bin/python
#coding: utf-8

################################
# file: log.py                 #
# function:  log               #
# author: xsseroot@gmail.com   #
# time: 2014-9-2 20:03         #
################################

import logging
import os
from logging.handlers import RotatingFileHandler

class loger():
	__log_level = None
	__log_format = "[%(asctime)s][%(filename)s line:%(lineno)d][pid=%(process)d][thread id=%(thread)d][%(levelname)s] %(message)s"
	__log_datefmt = ""
	__log_dir = "logs"
	__log_filename = ""
	__log_filemode = "w"
	__log_path = ""
	
	def __init__(self,logfileName="mm_crawler.log",log_level=None):
		if log_level:
			self.__log_level = log_level
		else:
			self.__log_level = logging.DEBUG
		# create 'logs' directory.
		path = os.getcwd() + "/" + self.__log_dir
		if not os.path.exists(path):
			os.mkdir(path)
		# set logging parameters
		self.__log_filename = logfileName	
		self.__log_path = "./%s/%s" % (self.__log_dir,self.__log_filename)
		logging.basicConfig(level = self.__log_level,
							format = self.__log_format,
							datefmt = self.__log_datefmt,
							filename = self.__log_path,
							filemode = self.__log_filemode
							)
		self.__ConsoleDisplay()
		self.__SetRotating()
		
	# console display						
	def __ConsoleDisplay(self):
		console = logging.StreamHandler()
		console.setLevel(self.__log_level)
		formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
		console.setFormatter(formatter)
		logging.getLogger('').addHandler(console)
	
	# set log Rotating
	def __SetRotating(self):
		RtHandler = RotatingFileHandler(self.__log_path, maxBytes=10*1024*1024,backupCount=30)
		RtHandler.setLevel(self.__log_level)
		formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
		RtHandler.setFormatter(formatter)
		logging.getLogger('').addHandler(RtHandler)
		
	# log debug	 level	output				
	def Debug(self,msg):		
		logging.debug(msg)
		#print "[Debug]",msg
	
	# log Info level output
	def Info(self,msg):
		logging.info(msg)
		#print "[Info]",msg
	
	# log Warning level output
	def Warning(self,msg):
		logging.warning(msg)
		#print "[Warning]",msg
	
	# log error level output
	def Error(self,msg):
		logging.error(msg)
		#print "[Error]",msg
	
	# log critical level output
	def Critical(self,msg):
		logging.critical(msg)
		#print "[Critical]",msg
